<?php

declare(strict_types=1);
// 账号登录
namespace app\admin_v1\controller;

use think\facade\Db; //门面模式
use app\admin_v1\model\Login as mysql; //导入模型

class Login
{
    public function index()
    {
        $query = request()->param(); //请求参数


        if (request()->header("token")) {
            $user_cache_name = md5(md5(app("http")->getName() . request()->ip()) . request()->header("token"));
            // return json(["code" => 201, "msg" => "header_token存在", "header_token" => request()->header("token"),]);
            if (cache($user_cache_name)) {
                // return json(["code" => 201, "msg" => "header_token相同的cache存在", "header_token" => request()->header("token"), "cache" => cache($user_cache_name)]);
                // return json(["code" => 201, "msg" => "禁止重复调用登录API", "header_token" => request()->header("token"), "cache" => cache($user_cache_name)]);
                cache($user_cache_name, null);
                return json(["code" => 201, "msg" => "登录状态下重复调用登录API-服务器已清除之前登录数据-请重新登录",]);
                $user_cache_avl = cache($user_cache_name);
                if ($user_cache_avl["header_token"]) {
                    return json(["code" => 201, "msg" => "cache内部header_token存在", "header_token" => request()->header("token"), "cache" => cache($user_cache_name)]);
                    if ($user_cache_avl["header_token"] == request()->header("token")) {
                        return json(["code" => 201, "msg" => "header_token与cache内部header_token相同", "header_token" => request()->header("token"), "cache" => cache($user_cache_name)]);
                    } else {
                        cache($user_cache_name, null);
                        return json(["code" => 201, "msg" => "header_token与cache内部header_token不相同,已清空cache", "header_token" => request()->header("token"), "cache" => cache($user_cache_name)]);
                    }
                } else {
                    cache($user_cache_name, null);
                    return json(["code" => 201, "msg" => "cache内部header_token不存在,已清空cache", "header_token" => request()->header("token"), "cache" => cache($user_cache_name)]);

                }
            }
        }

        $validate = new \app\admin_v1\validate\Login; //验证规则
        if (!$validate->check($query)) {
            // 验证不过关提示
            $api = [
                "code" => 201,
                "msg" => "请求有误-" . $validate->getError(),
                "validate" => $validate->getError(),
            ];
            return json($api);
        }
        // 匹配UID与密码
        $SQL_user_db = mysql::where([
            "uid" => $query["uid"],
            "pw" => md5($query["pw"])
        ])->field([
                    //返回以下字段：
                    "id",//禁止存储和引用_更新数据会删除本字段值_可用于快速查询
                    "dbid",//数据编号.唯一
                    "name",//名称
                    "uid",//登录帐号.唯一
                    "mobile",//登录手机.唯一
                    "email",//登录邮箱.唯一
                    "pw",//登录密码
                    "token",//登录令牌
                    "db_state",//数据状态
                    "state",//帐号状态_A正常B停用
                    "type",//类型_ADMIN-AGENT-VIP-WX-USER-POS
                    "time_login",//登录时间
                    "time_new",//创建时间
                    "time_up",//修改时间
                    "memo",//备注
                    "login_ip",//登录IP地址
                    "login_hits",//登录次数
                    "group_dbid",//集团数据编号
                    "branch_dbid",//机构数据编号
                    "departments_dbid",//部门数据编号
                    "vid",//雇员编号_可由上级随意更改
                ])
            ->find();
        if (!$SQL_user_db) {
            return json(["code" => 201, "time" => time(), "msg" => "登录失败-密码不匹配[87]"]);
        }

        // 检查是否正确的机构成员
        $branchdb = Db::name("admin__i_group_branch")->where([
            "dbid" => $SQL_user_db["branch_dbid"],//机构数据编号
            "vid" => $query["branch_vid"],//机构自编号_可由上级随意更改
        ])->find();
        if (!$branchdb) {
            return json(["code" => 201, "time" => time(), "msg" => "登录失败-机构成员不匹配[97]"]);
        }
        // 登录成功
        if ($SQL_user_db && $branchdb) {
            /** 制造请求头token */
            $header_token = md5($SQL_user_db["token"] . "md5(token)");
            /** 制造缓存名称=md5(md5(APP应用名+访问者IP)+$header_token) */
            $user_cache_name = md5(md5(app("http")->getName() . request()->ip()) . $header_token);
            /** 制造缓存值 */
            $cache_value = [
                "header_token" => $header_token,
                "userdb" => [
                    "time_login" => time(),//登录时间
                    "vid" => $SQL_user_db["vid"],//雇员编号_可由上级随意更改
                    "name" => $SQL_user_db["name"],//名称
                    "uid" => $SQL_user_db["uid"],//登录帐号.唯一
                ]
            ];
            cache($user_cache_name, $cache_value, 3600);//写用户缓存文件

            /** 更新用户数据库 */
            Db::name('admin__i_user')
                ->where([
                    "id" => $SQL_user_db["id"],
                    "dbid" => $SQL_user_db["dbid"],
                    "uid" => $query["uid"],
                ])
                ->update([
                    "token" => md5('USER-' . common__guid()["salt_any"]), //登录令牌
                    "time_login" => time(),//登录时间
                    "login_ip" => request()->ip(),//登录IP地址
                    "login_hits" => $SQL_user_db["login_hits"] ? $SQL_user_db["login_hits"] += 1 : 1,//登录次数
                ]);

            $api = [
                "code" => 200,
                "time" => time(),
                "msg" => "登录成功",
                // "query" => $query,
                "user_db" => $cache_value["userdb"],
                "header_token" => $header_token,
                // "_user_cache" => cache($user_cache_name),
                // "_user_cache_name" => $user_cache_name,
            ];
            return json($api);
        } else {
            return json(["code" => 201, "time" => time(), "msg" => "登录失败-意外[137]"]);
        }
    }

    /** 退出登录 */
    public function logout()
    {
        /** 缓存文件名=md5(md5(APP应用名+访问者IP)+$header_token) */
        $user_cache_name = md5(md5(app("http")->getName() . request()->ip()) . request()->header("token"));
        if (cache($user_cache_name)) {
            cache($user_cache_name, null);
            $api = ["code" => 200, "msg" => "退出登录成功"];
        } else {
            cache($user_cache_name, null);
            $api = ["code" => 201, "msg" => "退出登录失败"];
        }
        return json($api);
    }
}
